package com.cm.config;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @author chenming
 * @description
 * @create: 2022-11-24
 */
@Slf4j
@Configuration
public class MqttConfig {
    @Value("${mqtt.username}")
    private String username;

    @Value("${mqtt.password}")
    private String password;

    @Value("${mqtt.url}")
    private String url;

    @Value("${mqtt.client.id}")
    private String clientId;

    private MqttClient client;

    public void connect() {
        try {
            client = new MqttClient(url, clientId, new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            //是否清空session，设置false表示服务器会保留客户端的连接记录（订阅主题，qos）
            //客户端重连之后能获取到服务器在客户端断开连接期间推送的消息,
            //设置为true表示每次连接服务器都是新身份
            options.setCleanSession(true);
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            //连接超时，单位为秒
            options.setConnectionTimeout(100);
            //设置心跳时间 单位为秒，表示服务器每隔 1.5*20秒的时间向客户端发送心跳判断客户端是否在线
            options.setKeepAliveInterval(20);
            //设置遗嘱消息的话题，若客户端和服务器之间的连接意外断开，服务器将发布客户端的遗嘱信息
            //QoS服务质量，QoS0至多一次，QoS1至少一次，QoS2只有一次
            options.setWill("willTopic", (clientId + "与服务器断开连接").getBytes(), 0, false);
            client.setCallback(new MqttProviderCallback());
            client.connect(options);
        } catch (MqttException e) {
            log.error("Mqtt Server has broken.");
        }
    }

    @PostConstruct
    public void init() {
        connect();
    }

    public void publish(String topic, String message, int qos, boolean retained) {
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setQos(qos);
        mqttMessage.setRetained(retained);
        mqttMessage.setPayload(message.getBytes());
        MqttTopic mqttTopic = client.getTopic(topic);
        //提供一种机制跟踪消息的传递进度，以非阻塞方式执行发布时跟踪消息的传递进度
        MqttDeliveryToken token;
        try {
            //将指定消息发布到主题，但不等待消息传递完成，返回的token可用于跟踪消息的传递状态
            token = mqttTopic.publish(mqttMessage);
            token.waitForCompletion();
        } catch (MqttException e) {
            log.info("Mqtt publish failed.");
        }
    }

    /**
     * 订阅主题
     * @author xct
     * @param topic
     * @param qos
     * @return void
     * @date 2021/7/30 17:12
     */
    public void subscribe(String topic,int qos){
        try {
            client.subscribe(topic,qos);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}
